package com.example.graduation.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 邮件工具类
 *
 * @author Administrator
 */
@Service
@Slf4j(topic = "MailUtil")
public class MailUtil {
    private static final String REGISTER_MESSAGE = "清激活您的用户！";

    @Value("${mail.username}")
    private static String SEND_EMAIL;
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 用户注册时，发送邮件同时将激活码存入Redis
     *
     * @param to 用户邮箱
     */
    public void sendMail(String to) {
        String activeUuid = UUID.randomUUID().toString();
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            //发送邮件的用户名
            String from = SEND_EMAIL;
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(REGISTER_MESSAGE);
            messageHelper.setText(activeUuid, true);
            mailSender.send(messageHelper.getMimeMessage());
            //存储UUID至Redis中，邮件激活凭借UUID
            redisUtil.set(StringUtil.REGISTER_PREFIX + to, activeUuid, 300L, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.info("邮件发送失败 : {}", e.getMessage());
            return;
        }
        log.info("邮件发送成功!");
    }

    /**
     * 用户注册时，发送邮件同时将激活码存入Redis
     *
     * @param to 用户邮箱
     */
    public void sendMail(String to, String content) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            //发送邮件的用户名
            String from = "1010691328@qq.com";
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(REGISTER_MESSAGE);
            messageHelper.setText(content, true);
            mailSender.send(messageHelper.getMimeMessage());
        } catch (Exception e) {
            log.info("邮件发送失败 : {}", e.getMessage());
            return;
        }
        log.info("邮件发送成功!");
    }
}
